import {defHttp} from '/@/utils/http/axios';
import { useMessage } from "/@/hooks/web/useMessage";

const { createConfirm } = useMessage();

enum Api {
  list = '/followup/followUp/list',
  save = '/followup/followUp/add',
  edit = '/followup/followUp/edit',
  deleteOne = '/followup/followUp/delete',
  deleteBatch = '/followup/followUp/deleteBatch',
  importExcel = '/followup/followUp/importExcel',
  exportXls = '/followup/followUp/exportXls',
  // 子表
  followPlanList = '/followup/followUp/queryFollowPlanByMainId',
  followUpContentList = '/followup/followUp/queryFollowUpContentByMainId',
  // -- 新文件管理API --
  // 跟进计划
  uploadFollowPlanFile = '/followup/followUp/uploadFollowPlanFile',
  getFollowPlanFiles = '/followup/followUp/getFollowPlanFiles',
  getFollowPlanDetail = '/followup/followUp/getFollowPlanDetail',
  // 跟进记录
  uploadFollowUpFile = '/followup/followUp/uploadFollowUpFile',
  getFollowUpFiles = '/followup/followUp/getFollowUpFiles',
  getFollowUpDetail = '/followup/followUp/getFollowUpDetail',
  // 公用
  downloadFile = '/followup/followUp/downloadFile',
  previewFile = '/followup/followUp/previewFile',
  deleteFile = '/followup/followUp/deleteFile',
}

/**
 * 上传跟进计划文件
 * @param params FormData object containing file and followPlanId
 * @param onUploadProgress
 */
export const uploadFollowPlanFile = (params, onUploadProgress) => {
  const followPlanId = params.get('followPlanId');
  const file = params.get('file');

  return defHttp.uploadFile(
    {
      url: Api.uploadFollowPlanFile,
      onUploadProgress,
      params: { followPlanId: followPlanId },
    },
    {
      file: file,
    }
  );
};

/**
 * 上传跟进记录文件
 * @param params FormData object containing file and followUpContentId
 * @param onUploadProgress
 */
export const uploadFollowUpFile = (params, onUploadProgress) => {
  const followUpContentId = params.get('followUpContentId');
  const file = params.get('file');

  return defHttp.uploadFile(
    {
      url: Api.uploadFollowUpFile,
      onUploadProgress,
      params: {
        followUpContentId: followUpContentId,
      },
    },
    {
      file: file,
    }
  );
};

/**
 * 导出api
 * @param params
 */
export const getExportUrl = Api.exportXls;

/**
 * 导入api
 */
export const getImportUrl = Api.importExcel;

/**
 * 查询子表数据
 * @param params
 */
export const followPlanList = Api.followPlanList;

/**
 * 查询子表数据
 * @param params
 */
export const followUpContentList = Api.followUpContentList;


/**
 * 下载文件
 * @param fileId 文件ID
 */
export function downloadFile(fileId: string) {
  console.log('调用downloadFile API, fileId:', fileId);
  return defHttp.get({
    url: Api.downloadFile,
    params: { fileId },
    responseType: 'blob'
  }).then(response => {
    console.log('下载文件响应类型:', response.type);
    return response;
  }).catch(error => {
    console.error('下载文件错误:', error);
    throw error;
  });
}

/**
 * 获取跟进计划文件列表
 * @param followPlanId 跟进计划ID
 */
export function getFollowPlanFiles(followPlanId: string) {
  console.log('调用getFollowPlanFiles API, followPlanId:', followPlanId);
  return defHttp.get({
    url: Api.getFollowPlanFiles,
    params: { followPlanId }
  }).then(response => {
    console.log('获取跟进计划文件列表响应:', response);
    return response;
  }).catch(error => {
    console.error('获取跟进计划文件列表错误:', error);
    return [];
  });
}

/**
 * 获取跟进记录文件列表
 * @param followUpContentId 跟进记录ID
 */
export function getFollowUpFiles(followUpContentId: string) {
  return defHttp.get({
    url: Api.getFollowUpFiles,
    params: { followUpContentId },
  });
}

/**
 * 获取跟进计划详情（包含文件）
 * @param id 跟进计划ID
 */
export function getFollowPlanDetail(id: string) {
  console.log('调用getFollowPlanDetail API, id:', id);
  return defHttp.get({
    url: Api.getFollowPlanDetail,
    params: { id }
  }).then(response => {
    console.log('获取跟进计划详情响应:', response);
    return response;
  }).catch(error => {
    console.error('获取跟进计划详情错误:', error);
    return { record: {}, files: [] };
  });
}

/**
 * 获取跟进记录详情（包含文件）
 * @param id 跟进记录ID
 */
export function getFollowUpDetail(id: string) {
  return defHttp.get({
    url: Api.getFollowUpDetail,
    params: { id },
  });
}

/**
 * 删除文件
 * @param fileId 文件ID
 */
export function deleteFile(fileId: string) {
  console.log('调用deleteFile API, fileId:', fileId);
  return defHttp.delete({
      url: `${Api.deleteFile}?fileId=${fileId}`,
  }).then(response => {
    console.log('删除文件响应:', response);
    return response;
  }).catch(error => {
    console.error('删除文件错误:', error);
    throw error;
  });
}

/**
 * 获取文件访问URL
 * @param filePath 文件路径
 * @returns 完整的文件访问URL
 */
export function getFileAccessHttpUrl(filePath: string): string {
  if (!filePath) return '';
  
  // 如果是完整URL，直接返回
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath;
  }
  
  // 如果是相对路径，拼接基础URL
  const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
  
  // 确保路径以 / 开头
  const normalizedPath = filePath.startsWith('/') ? filePath : `/${filePath}`;
  
  // 返回完整URL
  return `${baseUrl}/followup/followUp/previewFile?fileId=${encodeURIComponent(normalizedPath)}`;
}

/**
 * 列表接口
 * @param params
 */
export const list = (params) =>
  defHttp.get({url: Api.list, params});

/**
 * 删除单个
 */
export const deleteOne = (params,handleSuccess) => {
  return defHttp.delete({url: Api.deleteOne, params}, {joinParamsToUrl: true}).then(() => {
    handleSuccess();
  });
}
/**
 * 批量删除
 * @param params
 */
export const batchDelete = (params, handleSuccess) => {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '是否删除选中数据',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      return defHttp.delete({url: Api.deleteBatch, data: params}, {joinParamsToUrl: true}).then(() => {
        handleSuccess();
      });
    }
  });
}

/**
 * 保存或者更新
 * @param params
 */
export const saveOrUpdate = (params, isUpdate) => {
  let url = isUpdate ? Api.edit : Api.save;
  return defHttp.post({url: url, params});
}
